package com.ruoyi.report.service.impl;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.docx.DocxFmtConvert;
import com.ruoyi.common.utils.jacob.Word2Pdf;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.report.domain.ReportInformation;
import com.ruoyi.report.mapper.ReportInformationMapper;
import com.ruoyi.report.service.IReportInformationService;
import com.ruoyi.report.service.IReportOrginalrecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报告信息Service业务层处理
 * 
 * @author luguanqing
 * @date 2020-11-17
 */
@Service
public class ReportInformationServiceImpl implements IReportInformationService
{
    @Autowired(required = false)
    private ReportInformationMapper reportInformationMapper;

    @Autowired
    private IReportOrginalrecordService reportOrginalrecordService;

    /**
     * 查询报告信息
     * 
     * @param id 报告信息ID
     * @return 报告信息
     */
    @Override
    public ReportInformation selectReportInformationById(String id)
    {
        return reportInformationMapper.selectReportInformationById(id);
    }

    /**
     * 查询报告信息列表
     * 
     * @param reportInformation 报告信息
     * @return 报告信息
     */
    @Override
    public List<ReportInformation> selectReportInformationList(ReportInformation reportInformation)
    {
        return reportInformationMapper.selectReportInformationList(reportInformation);
    }

    /**
     * 查询到期报告信息列表
     *
     * @param reportInformation 报告信息
     * @return 报告信息集合
     */
    @Override
    public List<ReportInformation> selectExpirationTime(ReportInformation reportInformation) {
        return reportInformationMapper.selectExpirationTime(reportInformation);
    }

    /**
     * 首页查询报告处理状态信息
     *
     * @param inspector
     */
    @Override
    public List<Map<String, Object>> selectCountByStatus(String inspector) {
        return reportInformationMapper.selectCountByStatus(inspector);
    }

    /**
     * 根据日期范围查询数据量
     *
     * @param dateLength
     */
    @Override
    public List<Map<String, Object>> selectReportNumByDate(Integer dateLength) {
        return reportInformationMapper.selectReportNumByDate(dateLength);
    }

    /**
     * 新增报告信息
     * 
     * @param reportInformation 报告信息
     * @return 结果
     */
    @Override
    public int insertReportInformation(ReportInformation reportInformation)
    {
        return reportInformationMapper.insertReportInformation(reportInformation);
    }

    /**
     *
     * @param state
     * @return
     */
    @Override
    public int selectReportInformationCount(String state) {
        return reportInformationMapper.selectReportInformationCount(state);
    }

    /**
     *
     * @param reportInformationList 报告数据列表
     * @return
     */
    @Override
    public String importReport(List<ReportInformation> reportInformationList) {
        if (StringUtils.isNull(reportInformationList) || reportInformationList.size() == 0)
        {
            throw new SecurityException("导入报告数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ReportInformation reportInformation : reportInformationList)
        {
            try
            {
                // 验证报告列表中是否存在报告编号
                ReportInformation r = this.selectReportInformationByNum(reportInformation.getReportNum());
                if (StringUtils.isNull(r))
                {
                    reportInformation.setState("6");
                    reportInformation.setId(IdUtils.fastSimpleUUID());
                    //导入报告列表
                    this.insertReportInformation(reportInformation);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、报告编号 " + reportInformation.getReportNum() + " 导入成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、报告编号 " + reportInformation.getReportNum() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、报告编号 " + reportInformation.getReportNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     *
     * @param reportNum
     * @return
     */
    @Override
    public ReportInformation selectReportInformationByNum(String reportNum) {
        return reportInformationMapper.selectReportInformationByNum(reportNum);
    }

    /**
     * 修改报告信息
     * 
     * @param reportInformation 报告信息
     * @return 结果
     */
    @Override
    public int updateReportInformation(ReportInformation reportInformation)
    {
        return reportInformationMapper.updateReportInformation(reportInformation);
    }


    /**
     * 签字处理报告内容
     * @param reportInformation
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int dealReport(ReportInformation reportInformation) {
        //获取报告路径
        String profile = RuoYiConfig.getProfile();
        //获取报告地址
        String contentAdress = reportInformation.getReportUrl();
        contentAdress = StringUtils.replace(contentAdress, "/profile", profile);
        //doc文件
        if(StringUtils.equals("doc",  StringUtils.substring(contentAdress, contentAdress.indexOf(".") + 1, contentAdress.length()))){
            //替换为docx文件，路径不变
            reportInformation.setReportUrl(reportInformation.getReportUrl() + "x");
            //内容路径
            DocxFmtConvert.convertDocFmt(contentAdress, 12);
            contentAdress = contentAdress + "x";
        }
        ReportInformation rf = new ReportInformation();
        //生成Pdf文件
        String pdfPath = StringUtils.substring(contentAdress, 0, contentAdress.lastIndexOf(".")) + ".pdf";
        Word2Pdf word2Pdf = new Word2Pdf();
        word2Pdf.word2pdfUtil(contentAdress, pdfPath);
        pdfPath = StringUtils.replace(pdfPath, profile, "/profile");
        rf.setId(reportInformation.getId());
        rf.setPdfReport(pdfPath);
        rf.setState("6");
        int ret = reportInformationMapper.updateReportInformation(rf);
        return ret;
    }


    /**
     * 首页统计报告情况
     * @param state
     * @return
     */
    @Override
    public List<HashMap<String, String>> selectCountByState(String state) {
        return reportInformationMapper.selectCountByState(state);
    }

    /**
     *
     * @param reportNum 报告编号，state 报告状态
     * @param state
     * @return
     */
    @Override
    public int updateReportStateByNum(String reportNum, String state) {
        return reportInformationMapper.updateReportStateByNum(reportNum, state);
    }

    /**
     *
     * @param id 报告编号，state 报告状态
     * @param state
     * @return
     */
    @Override
    public int updateReportStateById(String id, String state) {
        return reportInformationMapper.updateReportStateById(id, state);
    }

    /**
     * 批量归档
     * @param ids 报告id
     * @return
     */
    @Override
    public int updateBatchGd(String filier, String filiTime, String[] ids) {
        return reportInformationMapper.updateBatchGd(filier, filiTime, ids);
    }

    /**
     * 查询报告编号是否存在
     *
     * @param reportNum
     */
    @Override
    public int selectReportNumExits(String reportNum) {
        return reportInformationMapper.selectReportNumExits(reportNum);
    }

    /**
     * 批量下载
     * @param downer
     * @param downTime
     * @param ids 报告id
     * @return
     */
    @Override
    public int updateBatchDown(String downer, String downTime, String[] ids) {
        return reportInformationMapper.updateBatchDown(downer, downTime, ids);
    }

    /**
     * 根据报告id修改报告编号信息
     * @param reportInformation
     * @return
     */
    @Override
    public int updateReportInformationByBgbh(ReportInformation reportInformation) {
        return reportInformationMapper.updateReportInformationByBgbh(reportInformation);
    }

    /**
     *
     * @param reportInformation 报告信息
     */
    @Override
    public void reportSignature(ReportInformation reportInformation) {
        //String profile = RuoYiConfig.getProfile();
        ////获取报告内容地址
        //String contentAdress = reportInformation.getContentAdress();
        ////内容路径
        //contentAdress = StringUtils.replace(contentAdress, "/profile", profile);
        ////将签字参数存入
        //Map<String, Object> signatureMap = new HashMap<String, Object>(16);
        ////批准人和日期
        //if(StringUtils.isNotEmpty(reportInformation.getApprReg())){
        //    signatureMap.put("approval", reportInformation.getApprReg());
        //    signatureMap.put("appTime", DateUtils.formatDate(DateUtils.getNowDate(), DateUtils.CN_DATE_PATTERN));
        //}
        ////审核人和日期
        //if(StringUtils.isNotEmpty(reportInformation.getExamineReg())){
        //    signatureMap.put("examine", reportInformation.getExamineReg());
        //    signatureMap.put("exaTime", DateUtils.formatDate(DateUtils.getNowDate(), DateUtils.CN_DATE_PATTERN));
        //}
        ////主检人和日期
        //if(StringUtils.isNotEmpty(reportInformation.getChiefReg())){
        //    signatureMap.put("chiefInspector", reportInformation.getChiefReg());
        //    signatureMap.put("chiTime", DateUtils.formatDate(DateUtils.getNowDate(), DateUtils.CN_DATE_PATTERN));
        //}
        //Docx4jOPWord docx4jOPWord = new Docx4jOPWord();
        //docx4jOPWord.bookReplaceVarImg(contentAdress, contentAdress, signatureMap);
        ////将新的报告生成另存到onlyoffice的服务器上
        //try {
        //    FileUtils fileUtils = new FileUtils();
        //    String newContentName = StringUtils.substring(reportInformation.getContentAdress(), reportInformation.getContentAdress().lastIndexOf("/") + 1, reportInformation.getContentAdress().length());
        //    fileUtils.copyFile(contentAdress, RuoYiConfig.onlyOffice + newContentName);
        //}catch (Exception e){
        //    e.printStackTrace();
        //}
    }

    /**
     *
     * @param reportInformation 报告信息
     */
    @Override
    public void reportSimpleSign(ReportInformation reportInformation){
    }

    /**
     * 批量删除报告信息
     * 
     * @param ids 需要删除的报告信息ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteReportInformationByIds(String[] ids)
    {
        //根据报告id获取报告编号
        String[] bgbhs = reportInformationMapper.selectReportNumById(ids);
        //删除原始记录信息
        if(bgbhs.length > 0) {
            for(int i = 0; i < bgbhs.length; i++){
                reportOrginalrecordService.deleteReportOrginalrecordByReportNum(bgbhs[i]);
            }

        }
        //根据报告编号批量更新报告编号信息
        //if(bgbhs.length > 0) {
        //    List<String> bgbgList = new ArrayList();
        //    for(int i = 0; i < bgbhs.length; i++){
        //        bgbgList = StringUtils.str2List(bgbhs[i], ",", true, true);
        //    }
        //    bgbhMapper.updateBatchNZt(bgbgList);
        //}
        ////根据Id获取委托单号
        //for(int i = 0 ; i < ids.length; i++) {
        //    ReportInformation reportInformation = reportInformationMapper.selectReportInformationById(ids[i]);
        //    if(StringUtils.isNotEmpty(reportInformation.getAgreementNum())) {
        //        //变更委托单号状态
        //        entrustmentAgreementMapper.updateEntrustmentStateByNum("4", reportInformation.getAgreementNum());
        //    }
        //}
        return reportInformationMapper.deleteReportInformationByIds(ids);
    }

    /**
     *
     * @param reportNums 需要删除的报告编号
     * @return
     */
    @Override
    public int deleteReportInformationByNums(String[] reportNums) {
        return reportInformationMapper.deleteReportInformationByNums(reportNums);
    }

    /**
     * 删除报告信息信息
     * 
     * @param id 报告信息ID
     * @return 结果
     */
    @Override
    public int deleteReportInformationById(String id)
    {
        return reportInformationMapper.deleteReportInformationById(id);
    }

    /**
     * 删除报告信息信息
     *
     * @param reportNum
     * @return 结果
     */
    @Override
    public int deleteReportInformationByReportNum(String reportNum) {
        return reportInformationMapper.deleteReportInformationByReportNum(reportNum);
    }

    /**
     *
     * @param id
     * @param state
     * @return
     */
    @Override
    public String selectReasonById(String id, String state) {
        return reportInformationMapper.selectReasonById(id, state);
    }

    /**
     *
     * @param id
     * @return
     */
    @Override
    public String selectReportHistoryById(String id) {
        return reportInformationMapper.selectReportHistoryById(id);
    }

    /**
     *
     * @param ids
     * @return
     */
    @Override
    public String[] selectReportNumById(String[] ids) {
        return reportInformationMapper.selectReportNumById(ids);
    }


    /**
     *
     * @param ids
     * @return
     */
    @Override
    public List<ReportInformation> selectReportByIds(String[] ids) {
        return reportInformationMapper.selectReportByIds(ids);
    }
}
